package pub.tbc.toolkit.http;

import com.google.common.collect.Lists;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import pub.tbc.toolkit.Loops;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.function.BiConsumer;
import pub.tbc.toolkit.function.Consumer;

import java.util.List;
import java.util.Map;

/**
 * @author tbc on 2016/8/25 19:56:17.
 */
public class RequestTemplate {

    HttpRequestor http = new MyHttpImpl();

    /**
     * 用于GET请求，参数形式为URL路径，如/{id}
     * *#必须按顺序传数组参数
     *
     * @param url
     * @param param
     * @return
     */
    public String restTemplateGet(String url, String... param) {
        final StringBuilder sb = new StringBuilder();
        Loops.forEach(param, new Consumer<String>() {
            @Override
            public void accept(String s) {
                sb.append("/").append(s);
            }
        });

        final String uri = url + sb.toString();
        MyResponse response = http.get(uri);
        if (response.getCode() == 200) {
            return response.getResponse();
        }
        return null;
    }

    /**
     * 用于POST请求，CONTENT_TYPE为“application/json”，请求体传参
     *
     * @param url
     * @param param
     * @return
     */
    public String restTemplatePost(String url, Map<String, String> param) {
        List<NameValuePair> body = mapToBody(param);
        MyResponse response = http.post(url, HttpRequestor.CONTENT_TYPE_JSON, body);
        if (response.getCode() == 200) {
            return response.getResponse();
        }
        return null;
    }

    /**
     * 用于GET请求，参数形式为问号后跟参数
     *
     * @param url
     * @param param
     * @return
     */
    public String httpTemplateGet(String url, Map<String, String> param) {
        final StringBuilder sb = new StringBuilder(url);
        if (Objs.nonEmpty(param)) {
            sb.append("?");
            Loops.forEach(param, new BiConsumer<String, String>() {
                @Override
                public void accept(String k, String v) {
                    sb.append(k).append("=").append(v);
                }
            });
        }
        MyResponse response = http.get(sb.toString());
        if (response.getCode() == 200) {
            return response.getResponse();
        }
        return null;
    }

    private List<NameValuePair> mapToBody(final Map<String, String> param) {
        final List<NameValuePair> body = Lists.newArrayList();
        Loops.forEach(param.keySet(), new Consumer<String>() {
            @Override
            public void accept(String k) {
                body.add(new BasicNameValuePair(k, param.get(k)));
            }
        });
        return body;
    }
}
